package com.zm.authority.identity.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.zm.authority.identity.dao.ZmPermissionDao;
import com.zm.authority.identity.dao.ZmResourceDao;
import com.zm.authority.identity.dao.ZmRoleDao;
import com.zm.authority.identity.dao.ZmUserDao;
import com.zm.authority.identity.po.ZmUser;
import com.zm.authority.identity.service.IdentityService;
import com.zm.base.core.controller.VerifyCodeController;
import com.zm.base.core.exception.BaseException;
import com.zm.base.core.po.ZmResult;
import com.zm.common.core.util.AccentUtil;
import com.zm.common.core.util.Constant;

/**
 * IdentityServiceImpl
 * @author DENG.ZHUO.HUI
 * @email 13751827792@163.com
 * @date 2017年4月18日
 * @version 1.0
 */
@Service("identityService")
public class IdentityServiceImpl implements IdentityService {
	@javax.annotation.Resource(name="zmRoleDao")
	private ZmRoleDao zmRoleDao;
	@javax.annotation.Resource(name="zmUserDao")
	private ZmUserDao zmUserDao;
	@javax.annotation.Resource(name="zmResourceDao")
	private ZmResourceDao zmResourceDao;
	@javax.annotation.Resource(name="zmPermissionDao")
	private ZmPermissionDao zmPermissionDao;
	
	@javax.annotation.Resource(name="cacheManager")
	private CacheManager cacheManager;
	
	@Value("${mainMenuCacheName}")
	private String menuCacheName;
	private Cache<String,List<Map<String, Object>>> menuCache;
	
	@Value("${authorizationCacheName}")
	private String authorizationCacheName;
	private Cache<PrincipalCollection,AuthorizationInfo> authorizationCache;
	
	@PostConstruct
	public void init(){
		menuCache = cacheManager.getCache(menuCacheName);
		authorizationCache = cacheManager.getCache(authorizationCacheName);
	}
	
	@Override
	public ZmResult login(String userName, String password, String rememberMe,String verifyCode)throws BaseException,Exception {
		Subject subject = SecurityUtils.getSubject();

		String vCode = (String) subject.getSession().getAttribute(VerifyCodeController.VERIFY_CODE);
		if(verifyCode != null && verifyCode.equals(vCode)){
			
			if(!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(password)){
				
				UsernamePasswordToken token = new UsernamePasswordToken(userName,password,Constant.USER_REMEMBER_ME.equals(rememberMe));
				try {
					subject.login(token);
					//查询用户
					ZmUser user=zmUserDao.getUserByUserName(userName);
					subject.getSession().setAttribute(Constant.USER_IN_SESSION,user);
				} catch (AuthenticationException e) {
					e.printStackTrace();
					return ZmResult.build(3, "登录失败，用户名或密码不正确");
				}
				return ZmResult.ok();
			}else {
				return ZmResult.build(2, "用户名和密码不能为空");
			}
		}
		return ZmResult.build(1, "验证码不正确");
	}
	
	//MING  TODO
	//--------------------------用户---------------------------
	@Override
	public ZmUser getUserByUserName(String userName) throws BaseException, Exception {
		if(AccentUtil.isEmpty(userName)){
			return null;
		}
		ZmUser user=zmUserDao.getUserByUserName(userName);
		return zmUserDao.getUserByUserName(userName);
	}
	
	@Override
	public Set<String> getRolesByUserId(String userId)throws BaseException,Exception {
		List<String> roleCode = zmRoleDao.getRolesByUserId(userId);
		Set<String> roleCodeSet = new HashSet<>();
		roleCodeSet.addAll(roleCode);
		return roleCodeSet;
	}

	@Override
	public Set<String> getPermissionsByRoleIds(String[] roles) throws BaseException, Exception {
		if(AccentUtil.isEmpty(roles)){
			return null;
		}
		List<String> permissions=zmPermissionDao.getPermissionsByRoleIds(roles);
		Set<String> permissionSet=null;
		if(null!=permissions&&!"".equals(permissions)){
			permissionSet = new HashSet<>();
			permissionSet.addAll(permissions);
		}
		return permissionSet;
	}
}
